<template>
  <div>
    <el-dialog
      title="选择位置"
      :visible.sync="innerVisible"
      width="60%"
      top="5vh"
      @closed="resetMap"
    >
      <!-- 搜索框 -->
      <el-input
        v-model="addressKeyword"
        placeholder="输入地址搜索"
        size="small"
        clearable
        @input="handleInput"
        style="margin-bottom: 8px;"
      >
        <template slot="append">
          <el-button size="small" @click="searchAddress">搜索</el-button>
        </template>
      </el-input>

      <!-- 搜索结果 -->
<!--      <el-table-->
<!--        v-if="searchResults.length"-->
<!--        :data="searchResults"-->
<!--        size="small"-->
<!--        border-->
<!--        style="margin-bottom: 8px;"-->
<!--        max-height="150"-->
<!--        @row-click="selectSearchResult"-->
<!--        @row-dblclick="confirmSearchResult"-->
<!--      >-->
<!--        <el-table-column prop="name" label="名称" min-width="200" />-->
<!--        <el-table-column prop="address" label="地址" min-width="400" />-->
<!--      </el-table>-->
      <!-- 搜索结果浮层（替代 el-table） -->
      <div
        v-if="searchResults.length"
        class="search-suggestion-panel"
      >
        <div
          class="suggest-item"
          v-for="(item, index) in searchResults"
          :key="index"
          @click="selectSearchResult(item)"
        >
          <div class="suggest-title">{{ item.name }}</div>
          <div class="suggest-address">{{ item.address }}</div>
        </div>
      </div>
      <!-- 地图 -->
      <div id="mapContainer" style="width: 100%; height: 500px;"></div>

      <!-- 选中结果 -->
      <div style="margin-top: 8px;">
        <span>经度：{{ tempLocation.lng || '-' }}</span>
        <span style="margin-left: 20px;">纬度：{{ tempLocation.lat || '-' }}</span>
        <span style="margin-left: 20px;">地址：{{ tempLocation.address || '-' }}</span>
      </div>

      <span slot="footer">
        <el-button @click="innerVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmLocation">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import { Message } from 'element-ui'

export default {
  props: {
    value: { type: Object, default: () => ({ lng: null, lat: null }) },
    visible: { type: Boolean, default: false }
  },
  data() {
    return {
      innerVisible: this.visible,
      mapInstance: null,
      marker: null,
      geocoder: null,
      tempLocation: { lng: null, lat: null, address: '' },
      addressKeyword: '',
      searchResults: [],
      debounceTimer: null
    }
  },
  watch: {
    visible(val) {
      this.innerVisible = val
      if (val) {
        this.$nextTick(() => this.initMap())
      }
    },
    innerVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    initMap() {
      if (this.mapInstance) return
      // 打印 key 和安全码
      console.log('AMAP Key:', process.env.VUE_APP_AMAP_KEY)
      console.log('AMAP SecurityJsCode:', process.env.VUE_APP_AMAP_SECURITY)
      window._AMapSecurityConfig = {
        securityJsCode: process.env.VUE_APP_AMAP_SECURITY
      }

      AMapLoader.load({
        key: process.env.VUE_APP_AMAP_KEY,
        version: '2.0',
        plugins: ['AMap.Geocoder', 'AMap.PlaceSearch', 'AMap.Marker']
      }).then(AMap => {
        this.mapInstance = new AMap.Map('mapContainer', {
          zoom: 15,
          center: [this.value.lng || 113.6866, this.value.lat || 31.2586]
        })

        this.geocoder = new AMap.Geocoder({ city: '安陆' })

        if (this.value.lng && this.value.lat) {
          this.marker = new AMap.Marker({
            map: this.mapInstance,
            position: [this.value.lng, this.value.lat]
          })
          this.updateTempLocation(this.value.lng, this.value.lat)
        }

        this.mapInstance.on('click', e => {
          const { lng, lat } = e.lnglat
          if (!this.marker) {
            this.marker = new AMap.Marker({ map: this.mapInstance, position: e.lnglat })
          } else {
            this.marker.setPosition(e.lnglat)
          }
          this.updateTempLocation(lng, lat)
        })
      })
    },

    updateTempLocation(lng, lat) {
      this.tempLocation.lng = lng
      this.tempLocation.lat = lat
      if (this.geocoder) {
        this.geocoder.getAddress([lng, lat], (status, result) => {
          this.tempLocation.address =
            status === 'complete' && result.regeocode
              ? result.regeocode.formattedAddress
              : ''
        })
      }
    },

    searchAddress() {
      if (!this.addressKeyword) {
        Message.warning('请输入地址关键字')
        return
      }
      if (!this.mapInstance) return

      const placeSearch = new AMap.PlaceSearch({
        city: '武汉',
        pageSize: 10,
        pageIndex: 1,
        extensions: 'all'
      })

      placeSearch.search(this.addressKeyword, (status, result) => {
        if (status === 'complete' && result.poiList?.pois?.length) {
          this.searchResults = result.poiList.pois.map(p => ({
            name: p.name,
            address: `${p.pname || ''}${p.cityname || ''}${p.adname || ''}${p.address || ''}`,
            location: p.location
          }))
        } else {
          this.searchResults = []
          Message.warning('未找到匹配地址')
        }
      })
    },

    handleInput() {
      clearTimeout(this.debounceTimer)
      this.debounceTimer = setTimeout(() => {
        if (this.addressKeyword.trim()) this.searchAddress()
        else this.searchResults = []
      }, 600)
    },

    selectSearchResult(row) {
      this.searchResults = []
      if (!row.location) return
      const { lng, lat } = row.location
      const lnglat = [lng, lat]
      this.mapInstance.setCenter(lnglat)
      this.mapInstance.setZoom(16)
      if (!this.marker) this.marker = new AMap.Marker({ map: this.mapInstance, position: lnglat })
      else this.marker.setPosition(lnglat)
      Object.assign(this.tempLocation, { lng, lat, address: row.address })
    },

    confirmSearchResult(row) {
      this.selectSearchResult(row)
      this.confirmLocation()
    },

    confirmLocation() {
      if (!this.tempLocation.lng) {
        Message.warning('请先选择位置')
        return
      }
      this.$emit('input', { ...this.tempLocation })
      this.innerVisible = false
    },

    resetMap() {
      this.mapInstance = null
      this.marker = null
      this.geocoder = null
      this.searchResults = []
      this.addressKeyword = ''
      this.tempLocation = { lng: null, lat: null, address: '' }
    }
  }
}
</script>

<style scoped>
/* 搜索下拉浮层 */
.search-suggestion-panel {
  position: absolute;
  z-index: 9999;
  width: calc(60% - 40px); /* 和对话框的输入框对齐 */
  max-height: 220px;
  overflow-y: auto;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
  margin-top: -6px; /* 让它紧贴输入框下方 */
}

/* 单条建议 */
.suggest-item {
  padding: 8px 12px;
  cursor: pointer;
  line-height: 1.4;
}

.suggest-item:hover {
  background: #f5f7fa;
}

/* 名称加粗 */
.suggest-title {
  font-weight: 600;
  font-size: 14px;
  color: #333;
}

/* 地址次要文案 */
.suggest-address {
  font-size: 12px;
  color: #888;
  margin-top: 2px;
}

#mapContainer {
  border: 1px solid #ccc;
}
</style>
